const {endPool} = require('./src/mysql/mysql');

const {getNytConnection, query} = require('./src/mysql/mysql');

/*
 *  首页入口
 *
 */

const {queryAccountUserNames} = require('./src/nyt/account'); //农业厅库

const {queryAccountUserNames: queryCoreAccountUserNames} = require('./src/core/account'); //核心平台库

const {logger} = require('./src/log4j');

const {Promise} = require('bluebird');

const {insert, getCoreConnection, beginTX} = require('./src/mysql/mysql');

const {exec} = require('child_process');

const PromiseExec = Promise.promisify(exec);

const moment = require('moment');

const {defaultValue} = require('./src/utils/Number');

async function index() {
    let coreConnection, nytConnection;
    try {
        coreConnection = await getCoreConnection();
        nytConnection = await getNytConnection();
        coreConnection = await beginTX(coreConnection);
        const [nytUsers, coreUsers] = await Promise.all([queryAccountUserNames(), queryCoreAccountUserNames()]);
        let newUsers = [];
        for (let item of nytUsers) {
            if (_contains(coreUsers, item)) {
                continue;
            } else {
                newUsers.push(item);
            }
        }

        // logger.debug(newUsers.length);
        // logger.debug(newUsers);
        // 同步农业厅的数据到核心平台
        for (let user of newUsers) {

            //创建账户表
            // logger.debug();
            const accountSql = `insert into account (username,password,type,valid,is_auth,last_login_time,create_time,data_id,email_checked,is_agr_business)
         values('${user.username}','${user.password}',1,${user.valid},${user.is_auth},'${moment(user.last_login_time).format("YYYY-MM-DD HH:mm:ss")}','${moment(user.create_time).format("YYYY-MM-DD HH:mm:ss")}',${user.data_id},${user.email_checked},0)`;
            const accountResult = await insert(coreConnection, accountSql);
            if (accountResult.affectedRows > 0) {

                logger.debug('账户表插入成功,用户名是:' + user.username + ' 用户id是:' + accountResult.insertId);
                //查询农业厅中的企业信息 根据user.id
                const companyQuerySql = `select * from company where account_id = ${user.id}`;
                const {rows} = await query(nytConnection, companyQuerySql);
                // logger.debug(rows);
                if (rows != null && rows.length > 0) {
                    const nytCompany = rows[0];
                    // logger.debug(nytCompany);
                    //插入企业信息
                    const companySql = `insert into company (account_id, no, logo, name, addr, area_names,
                     area_ids, reg_capital, reg_time, reg_type, tel, email, website, info,
                tags, trade_ids, trade_names, attent_num, phone, linkman , service, recommend, hot, latest , recommend_num,
                hot_num, latest_num, create_time, ltqy_type, employees, main_products, valid, trade_child_ids, trade_child_names,
                recommend_trade, update_time , mark, org_code, business_licence, comp_auth, choose, type, tel_show, raw_materis,
                stats_password, annual_turnover, contact_id, fax, general_manager_name, general_manager_phone, material_ids,
                material_names, material_type_ids, material_type_names, other_material_name) values (
                ${accountResult.insertId},'${nytCompany.no}','${nytCompany.logo}',
                '${nytCompany.name}','${nytCompany.addr}',
                '${nytCompany.area_names}','${nytCompany.area_ids}','${nytCompany.reg_capital}'
                ,'${nytCompany.reg_time}',${nytCompany.reg_type},'${nytCompany.tel}','${nytCompany.email}',
                '${nytCompany.website}','${nytCompany.info}',
                '${nytCompany.tags}','${nytCompany.trade_ids}','${nytCompany.trade_names}',
                ${defaultValue(nytCompany.attent_num, 0)},'${nytCompany.phone}','${nytCompany.linkman}',
                '${nytCompany.service}',${defaultValue(nytCompany.recommend, 0)}
                ,${defaultValue(nytCompany.hot, 0)},${defaultValue(nytCompany.latest, 0)},${defaultValue(nytCompany.recommend_num, 0)},
                ${defaultValue(nytCompany.hot_num, 0)},${defaultValue(nytCompany.latest_num, 0)},
                '${moment(nytCompany.create_time).format("YYYY-MM-DD HH:mm:ss")}',
                ${defaultValue(nytCompany.ltqy_type, 0)},${defaultValue(nytCompany.employees, 0)},'${nytCompany.main_products}',
                ${defaultValue(nytCompany.valid, 0)},'${nytCompany.trade_child_ids}','${nytCompany.trade_child_names}',
                '${nytCompany.recommend_trade}','${moment(nytCompany.update_time).format("YYYY-MM-DD HH:mm:ss")}','${nytCompany.mark}',
                '${nytCompany.org_code}','${nytCompany.business_licence}','${defaultValue(nytCompany.comp_auth, 0)}'
                ,'${nytCompany.choose}',${defaultValue(nytCompany.type, 0)},${defaultValue(nytCompany.tel_show, 0)},
                '${nytCompany.raw_materis}','${nytCompany.stats_password}',
                '${defaultValue(nytCompany.annual_turnover, 0)}','${defaultValue(nytCompany.contact_id, 0)}','${nytCompany.fax}',
                '${nytCompany.general_manager_name}','${nytCompany.general_manager_phone}',
                '${nytCompany.material_ids}','${nytCompany.material_names}'
                ,'${nytCompany.material_type_ids}','${nytCompany.material_type_names}',
                '${nytCompany.other_material_name}'
                )`;
                    const companyResult = await insert(coreConnection, companySql);
                    if (companyResult.affectedRows > 0) {
                        logger.debug('企业表插入成功,企业名是:' + nytCompany.name + ' 用户id是:' + user.id);
                        //插入企业状态表和审核表
                        const {rows: nytCompStatuses} = await query(nytConnection, `select * from comp_status where account_id = ${user.id}`);
                        // logger.debug(nytCompStatus);
                        if (nytCompStatuses != null && nytCompStatuses.length > 0) {

                            const compStatusSql = `insert into comp_status(account_id,base,tech,achv,product,yfnl,fund,expo,auth) values(

                            ${accountResult.insertId},${nytCompStatuses[0].base},${nytCompStatuses[0].tech},${nytCompStatuses[0].achv},${nytCompStatuses[0].product},
                            ${nytCompStatuses[0].yfnl},${nytCompStatuses[0].fund},${nytCompStatuses[0].expo},${nytCompStatuses[0].auth}
                        )`;
                            await insert(coreConnection, compStatusSql);
                            logger.debug('企业状态表数据插入成功');
                        }

                        const accountAuditSql = `select * from account_audit where account_id = ${user.id}`;
                        const {rows: accountAudits} = await query(nytConnection, accountAuditSql);
                        // logger.debug(accountAudits);
                        if (accountAudits != null && accountAudits.length > 0) {


                            const accountAudit = accountAudits[0];
                            // logger.debug(accountAudit);
                            const accountAuditInsertSql = `insert into account_audit(account_id,first_audit_id,first_audit_date,second_audit_id,second_audit_date,second_audit_remark,status) values(

                            ${accountResult.insertId},
                            ${accountAudit.first_audit_id},
                            ${accountAudit.first_audit_date != null ? '\'' + moment(accountAudit.first_audit_date).format("YYYY-MM-DD HH:mm:ss") + '\'' : null},
                            ${accountAudit.second_audit_id},
                            ${accountAudit.second_audit_date != null ? '\'' + moment(accountAudit.second_audit_date).format("YYYY-MM-DD HH:mm:ss") + '\'' : null},
                            ${accountAudit.second_audit_remark},
                            ${accountAudit.status}
                        )`;
                            await insert(coreConnection, accountAuditInsertSql);
                            logger.debug('账户审核表数据插入成功');
                        }

                        //图片处理 logo 跟 营业执照
                        //调用系统命令
                        //logo
                        // logger.debug(nytCompany.logo);
                    }
                }

            }
        }
        coreConnection.commit();
    }
    catch (err) {
        logger.error(err);
        coreConnection.rollback();

    } finally {
        // coreConnection.release();
        // nytConnection.release();
        logger.debug('finally');
        endPool();
    }

}

/**
 *
 * @param originArray
 * @param item
 * @private
 */
function _contains(originArray, item) {

    if (originArray != null && originArray.length > 0) {

        const sameIndex = originArray.findIndex((value, index, array) => {
            return item.username == value.username;
        });
        if (sameIndex >= 0) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

index();